import os
import json
import requests

done_file_path = "done.txt"

def read_done(done_file):
    # 读取 JSON 文件
    with open(done_file, "r", encoding="utf-8") as file:
        data = file.readlines()
    urls = [item.replace("\n","") for item in data]
    return urls

def append_done(done_file , txt):
    # 追加内容
    with open(done_file, "a", encoding="utf-8") as file:
        file.write(f"\n{txt}")

def download_video_from_json(done_video_urls, json_file, save_dir):
    # 确保保存目录存在
    os.makedirs(save_dir, exist_ok=True)

    # 读取 JSON 文件
    with open(json_file, "r", encoding="utf-8") as file:
        data = json.load(file)

    videos = [dict(title=item["title"], url=item["url"]) for item in data]
    # 提取 MP4 视频 URL 列表（假设 JSON 里存的是一个列表）
    print(videos)

    if not videos:
        print("未找到任何 MP4 视频 URL")
        return

    # 下载每个视频
    for index, video_info in enumerate(videos):
        try:
            title = video_info["title"]
            video_url = video_info["url"]
            if video_url in done_video_urls:
                continue
            if video_url == "":
                continue

            print(f"正在下载视频 {index + 1}, title : {video_url}")
            response = requests.get(video_url, stream=True)
            response.raise_for_status()

            # 文件名
            file_name = os.path.join(save_dir, f"{title}.mp4")

            # 保存视频文件
            with open(file_name, "wb") as file:
                for chunk in response.iter_content(chunk_size=1024 * 1024):
                    file.write(chunk)

            append_done(done_file_path, video_url)
            print(f"视频 {title} 下载完成: {file_name}")

        except requests.exceptions.RequestException as e:
            print(f"下载失败: {title} , {video_url}，错误: {e}")


done_video_urls = read_done(done_file_path)


json_file_path = "pmbok课程.json"
save_directory = "/Users/daxiang/Documents/pmbok"
download_video_from_json(done_video_urls, json_file_path, save_directory)